package net.kesumu.yushabu;

import java.net.URI;
import java.net.URLEncoder;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import net.kesumu.general.android.EasyStorage.EasyStorage;
import net.kesumu.general.android.view.BackgroundUtil;
import net.kesumu.general.android.view.CustomStatusBar;
import net.kesumu.yushabu.utils.JSONUtil;
import net.kesumu.yushabu.utils.WsConfig;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import com.codebutler.android_websockets.WebSocketClient;
import com.umeng.message.PushAgent;

import net.kesumu.yushabu.R;

public class EditInfoActivity extends Activity {
    
    public static final String TYPE_EDIT_NAME = "editName",
                               TYPE_EDIT_YUYUCHATID = "editYuYuChatId",
                               TYPE_EDIT_SIGNATURE = "editSignature",
                               TYPE_EDIT_GENDER = "editGender",
                               TYPE_EDIT_AREA = "editArea";
    
    private String type;
    private EasyStorage mEasyStorage;
    
    
    TextView mNameView;
    TextView mIdView;
    TextView mSignatureView;
    TextView mGenderView;
    TextView mAreaView;
    
    TextView mTextMessageView;

    String mMyPhotoPath;
    String mMyName;
    String mMyId;
    String mMySignature;
    String mMyGender;
    String mMyArea;
    String mYuYuChatId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_info);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); 
        getActionBar().setCustomView(R.layout.actionbar);
        ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.title_activity_edit_info));
        //Custom the status bar
        CustomStatusBar customStatusBar = new CustomStatusBar(this);
        customStatusBar.setStatusBarColor(findViewById(R.id.statusBarBackground), getResources().getColor(R.color.main));


        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        
        Intent receivedIntent = getIntent();
        type = receivedIntent.getStringExtra("type");
        
        mEasyStorage = new EasyStorage(this, getString(R.string.preference_file_key));
        mMyPhotoPath = mEasyStorage.getString("mMyPhotoPath");
        mMyName = mEasyStorage.getString("mMyName");
        mMyId = mEasyStorage.getString("mMyId");
        mMySignature = mEasyStorage.getString("mMySignature");
        mMyGender = mEasyStorage.getString("mMyGender");
        mMyArea = mEasyStorage.getString("mMyArea");
        mYuYuChatId = mEasyStorage.getString("mYuYuChatId");
        
        startUpClient();
        
        PushAgent.getInstance(this).onAppStart();
    }
    
    @Override
    protected void onStart() {
        mNameView = (TextView) findViewById(R.id.text_name_edit);
        mIdView = (TextView) findViewById(R.id.text_yuyuChatId_edit);
        mSignatureView = (TextView) findViewById(R.id.text_signature_edit);
        mGenderView = (TextView) findViewById(R.id.text_gender_edit);
        mAreaView = (TextView) findViewById(R.id.text_area_edit);
        
        if(type.equalsIgnoreCase(TYPE_EDIT_NAME)) {
            findViewById(R.id.parent_text_name_edit).setVisibility(View.VISIBLE);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.name));
            mTextMessageView = mNameView;
        }else if(type.equalsIgnoreCase(TYPE_EDIT_YUYUCHATID)) {
            findViewById(R.id.parent_text_yuyuChatId_edit).setVisibility(View.VISIBLE);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.yuyuChatId));
            mTextMessageView = mIdView;
        }else if(type.equalsIgnoreCase(TYPE_EDIT_SIGNATURE)) {
            findViewById(R.id.parent_text_signature_edit).setVisibility(View.VISIBLE);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.signature));
            mTextMessageView = mSignatureView;
        }else if(type.equalsIgnoreCase(TYPE_EDIT_GENDER)) {
            findViewById(R.id.parent_text_gender_edit).setVisibility(View.VISIBLE);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.gender));
            mTextMessageView = mGenderView;
        }else if(type.equalsIgnoreCase(TYPE_EDIT_AREA)) {
            findViewById(R.id.parent_text_area_edit).setVisibility(View.VISIBLE);
            ((TextView)findViewById(R.id.actionbar_title)).setText(getString(R.string.area));
            mTextMessageView = mAreaView;
        }

        mNameView.setText(mMyName);
        mIdView.setText(mYuYuChatId);
        mSignatureView.setText(mMySignature);
        mGenderView.setText(mMyGender);
        mAreaView.setText(mMyArea);
        
        mTextMessageView.requestFocus(MODE_APPEND);
        mTextMessageView.setImeActionLabel(getResources().getString(R.string.btn_modify), 
                                                            KeyEvent.KEYCODE_ENTER);
        mTextMessageView.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    userInfoModify();
                    handled = true;
                }
                return handled;
            }
        });
        
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.edit_info, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.myInfo_modify) {
            userInfoModify();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_edit_info,
                    container, false);
            return rootView;
        }
    }
    
    public void userInfoModify() {
        boolean changed = false;
        String new_mMyName = "";
        String new_mMyGender = "";
        String new_mMyArea = "";
        String new_mMySignature = "";
        String new_mYuYuChatId = "";
        if(mNameView.getText() != null) {
            new_mMyName = mNameView.getText().toString();
        }
        if(mGenderView.getText() != null) {
            new_mMyGender = mGenderView.getText().toString();
        }
        if(mAreaView.getText() != null) {
            new_mMyArea = mAreaView.getText().toString();
        }
        if(mSignatureView.getText() != null) {
            new_mMySignature = mSignatureView.getText().toString();
        }
        if(mIdView.getText() != null) {
            new_mYuYuChatId = mIdView.getText().toString();
        }
        
        if(isChanged(mMyName, new_mMyName) || 
           isChanged(mMyGender, new_mMyGender) ||
           isChanged(mMyArea, new_mMyArea)||
           isChanged(mMySignature, new_mMySignature)||
           isChanged(mYuYuChatId, new_mYuYuChatId)) {
            changed = true;
        }
        
        if(changed == true) {
            sendRequest(jsonUtil.getUserInfoModifyJSON(mMyId, new_mMyName, new_mYuYuChatId, new_mMySignature, new_mMyGender, new_mMyArea));
        }else {
            //go back to the previous activity
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    finish();
               }
            });
        }
    }
    
    public boolean isChanged(String oldValue, String newValue) {
        boolean result = false;
        if(oldValue == null) {
            if(newValue != null && newValue != "") {
                result = true;
            }
        }else {
            if(!oldValue.equals(newValue)) {
                result = true;
            }
        }
        return result;
    }
    
    


    
    @Override
    protected void onDestroy() {
        if(client != null && client.isConnected()) {
            client.disconnect();
            client = null;
        }
        super.onDestroy();
    }
    
    /**
     * Connection with the server
     */
    private WebSocketClient client;
    private JSONUtil jsonUtil;
    void startUpClient() {
        if(client != null && client.isConnected()) {
            return;
        }
        jsonUtil = new JSONUtil(getApplicationContext());
        client = new WebSocketClient(URI.create(WsConfig.URL_WEBSOCKET
                + URLEncoder.encode(WsConfig.SESSION_TAG_DEFAULT)), new WebSocketClient.Listener() {
            public void onConnect() {

            }
            public void onMessage(String message) {
                parseMessage(message);
            }
            public void onMessage(byte[] data) {
                // Message will be in JSON format
                parseMessage(JSONUtil.bytesToHex(data));
            }
            public void onDisconnect(int code, String reason) {
                String message = String.format(Locale.US,
                        "Disconnected! Code: %d Reason: %s", code, reason);
                showToast(message);
            }
            public void onError(Exception error) {
                showToast("Error! : " + error);
            }
        }, null);
        client.connect();
    }

    //remove the null judge for immediately send a message after connection setup
    private void sendRequest(String message) {
        if(client != null && client.isConnected()) {
            client.send(message);
        }
    }
    
    private void parseMessage(final String msg) {
 
        try {
            JSONObject jObj = new JSONObject(msg);
 
            // JSON node 'flag'
            String flag = jObj.getString("flag");

            if (flag.equalsIgnoreCase(JSONUtil.FLAG_USERINFO_MODIFY)) {
                String result = jObj.getString("result");
                showToast(result);
                
                if(result.equalsIgnoreCase("success")) {
                    mMyName = mNameView.getText().toString();
                    mYuYuChatId = mIdView.getText().toString();
                    mMySignature = mSignatureView.getText().toString();
                    mMyGender = mGenderView.getText().toString();
                    mMyArea = mAreaView.getText().toString();
                    
                    mEasyStorage.putString("mMyName", mMyName);
                    mEasyStorage.putString("mYuYuChatId", mYuYuChatId);
                    mEasyStorage.putString("mMySignature", mMySignature);
                    mEasyStorage.putString("mMyGender", mMyGender);
                    mEasyStorage.putString("mMyArea", mMyArea);
                }
                
                //go back to the previous activity
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                   }
                });
                
            }
 
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    
    private void showToast(final String message) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_SHORT).show();
            }
        });
 
    }

}
